import React, { useEffect, useState } from 'react';
import {
    Card,
    CardContent,
    CardDescription,
    CardFooter,
    CardHeader,
    CardTitle,
} from "@/components/ui/card";
import { Bar, BarChart, ResponsiveContainer, Treemap, XAxis, YAxis, Tooltip } from "recharts"
import { Progress } from "@/components/ui/progress";
import { formatAmount } from '@/lib/tools';
import dayjs from 'dayjs';
export default function ({ statisticsData, details, className, onChartClick , month}) {
    const [mom, setMom] = useState(0);
    const [barData, setBarData] = useState([]);
    const [mapTreeData, setMapTreeData] = useState([]);
    const [title, setTitle] = useState('');
    useEffect(() => {
        const filterDate = month ? dayjs(`${month}-01`, 'YYYY-MM-DD') : dayjs();
        setTitle(`Month ${filterDate.format('YYYY/MM')}`)
    }, [month]);
    useEffect(() => {
        setBarData((statisticsData?.byDate || []).filter(item => item.days && item.trans_type === '支出').sort((a, b) => a.days - b.days).map(item => {
            return {
                name: item.days,
                amount: item.trans_amount
            }
        }).sort((a, b) => a.name - b.name));
        setMapTreeData((statisticsData?.byTag || []).filter(item => item.tag && item.trans_type === '支出').map(item => {
            return {
                name: item.tag,
                amount: parseInt(item.trans_amount)
            }
        }).sort((a, b) => b.amount - a.amount).slice(0, 20));
        const currentTotal = statisticsData?.total?.['支出']?.trans_amount || 0;
        const lastMonthTotal = statisticsData?.totalOfLastMonth?.['支出']?.trans_amount || 0;
        setMom(parseInt(lastMonthTotal > 0 ? ((currentTotal - lastMonthTotal) * 100 / lastMonthTotal) : 0));
    }, [statisticsData]);

    return (
        <Card x-chunk="dashboard-05-chunk-1" className={className}>
            <CardHeader className="pb-2">
                <div class="flex w-full">
                    <div class="flex-2">
                        <CardDescription>{title}</CardDescription>
                        <CardTitle className="text-4xl">￥{formatAmount(statisticsData?.total?.['支出']?.trans_amount) || '-'}</CardTitle>
                        <div class="text-xs text-muted-foreground mt-2">{mom > 0 ? `+${mom}` : (mom || '-')}% from last month({formatAmount(statisticsData?.totalOfLastMonth?.['支出']?.trans_amount || 0)})</div>
                    </div>
                    <div class="flex-1 ml-2" onClick={() => onChartClick?.('Ranking Chart By Month', barData, statisticsData.details, (items, value) => items.filter(item => item.trade_type === '支出' && item.days === value))}>
                        <ResponsiveContainer width="100%" height="100%">
                            <BarChart data={barData}>
                                <XAxis dataKey="name" hide />
                                <Bar
                                    dataKey="amount"
                                    style={{
                                        fill: "hsl(var(--primary))",
                                        opacity: 0.9,
                                    }}
                                />

                            </BarChart>
                        </ResponsiveContainer>
                    </div>
                </div>
            </CardHeader>
            <CardContent>
                <div class="flex w-full">
                    <div class="flex-2">
                        <div className="text-xs text-muted-foreground">
                            +{statisticsData?.budget?.rateOfDecrement || '-'}% budget decrement ({formatAmount(statisticsData?.budget?.total) || '0'})
                        </div>
                    </div>
                    <div class="flex-1 ml-2">
                        <Progress value={statisticsData?.budget?.rateOfDecrement || 100} />
                    </div>
                </div>
            </CardContent>
            <CardFooter>
                <div className="w-full mt-3 h-[120px]" onClick={() => onChartClick?.('Ranking Chart By Month Top20 Tag', mapTreeData, statisticsData.details, (items, value) => items.filter(item => item.trade_type === '支出' && item.tags.includes(value)))}>
                    <ResponsiveContainer width="100%" height="100%">
                        <Treemap width={400} height={200} data={mapTreeData} dataKey="amount" aspectRatio={4 / 3} stroke="#fff" isAnimationActive={false} style={{
                            fill: "hsl(var(--primary))",
                            opacity: 0.9,
                        }} >
                        </Treemap>
                    </ResponsiveContainer>
                </div>
            </CardFooter>
        </Card>
    )
}
